﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ProgrammingIsMyPassion.Coding
{
    //Problem
    //Rearrange array of int such as A[0] <= A[1] >= A[2] <= A[3]
    public class ReArrangeArrayProblem
    {
        public int[] Solution1(int[] A)
        {
            //Sort 
            Array.Sort(A);
            //swap items
            for (int i = 1; i < A.Length; i += 2)
            {
                this.Swap( A ,  i , i+1);
            }
            return A;
            //O(nlogn) + o(n) = O(nlogn)
        }

        private  void Swap( int[] A, int i , int j)
        {
            int temp = A[i];
            A[i] = A[j];
            A[j] = temp;
        }

        private  int GetSmallest( int[] A, int i, int j)
        {
            if (A[i] > A[j]) return j;
            return i;
        }
        private int GetLargest( int[] A, int i, int j)
        {
            if (A[i] > A[j]) return i;
            return j;
        }
        public int[] Solution2(int[] A)
        {

            for (int i = 1; i < A.Length - 1; i++)
            {
                if (i % 2 == 0)
                {
                    if (A[i] <= A[i - 1] && A[i] <= A[i + 1])
                        continue;
                    else
                    {
                        int smalli = GetSmallest(A, i - 1, i + 1);
                        Swap(A, i, smalli);
                    }
                }
                if (i % 2 != 0)
                {
                    if (A[i] >= A[i - 1] && A[i] >= A[i + 1])
                        continue;
                    else
                    {
                        int largei = GetLargest(A, i - 1, i + 1);
                        Swap(A, i, largei);
                    }
                }

            }
            return A;
        }

    }
}
